define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            // Table.api.init({
            //     extend: {
            //         index_url: 'meet/store/index' + location.search,
            //         add_url: 'meet/store/add',
            //         edit_url: 'meet/store/edit',
            //         del_url: 'meet/store/del',
            //         multi_url: 'meet/store/multi',
            //         import_url: 'meet/store/import',
            //         table: 'meet_store',
            //     }
            // });
            //
            // var table = $("#table");
            //
            // // 初始化表格
            // table.bootstrapTable({
            //     url: $.fn.bootstrapTable.defaults.extend.index_url,
            //     pk: 'id',
            //     sortName: 'weigh',
            //     fixedColumns: true,
            //     fixedRightNumber: 1,
            //     columns: [
            //         [
            //             {checkbox: true},
            //             {field: 'id', title: __('Id')},
            //             {field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'province_id', title: __('Province_id')},
            //             {field: 'city_id', title: __('City_id')},
            //             {field: 'county_id', title: __('County_id')},
            //             {field: 'address', title: __('Address'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'longitude', title: __('Longitude'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'latitude', title: __('Latitude'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'business_hours', title: __('Business_hours'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'telephone', title: __('Telephone'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
            //             {field: 'early_refund', title: __('Early_refund')},
            //             {field: 'status', title: __('Status'), searchList: {"hidden":__('Hidden'),"normal":__('Normal')}, formatter: Table.api.formatter.status},
            //             {field: 'weigh', title: __('Weigh'), operate: false},
            //             {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
            //             {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
            //             {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
            //         ]
            //     ]
            // });
            //
            // // 为表格绑定事件
            // Table.api.bindevent(table);

            $(document).on('click','.btn-location',function () {
                let location = $('#c-location').val();
                var url = '';
                if(location){
                    location = location.split(',');
                    url = 'meet/store/map?longitude='+location[0]+'&latitude='+location[1];
                }else{
                    url = 'meet/store/map';
                }
                Fast.api.open(url,__('Coordinate picking'),{
                    area:['90%','95%'],
                    callback:function (value) {
                        $('#c-location').val(value.location);
                    }
                });
            });

            if(!receiveUsers){
                receiveUsers = [];
            }

            Controller.api.fansTemplate(receiveUsers);

            $(document).on('click','.btn-wechat',function () {
                Fast.api.open('meet/store/fans',__('Select user'),{
                    callback: function (data) {
                        // 是否新增
                        let append = false;
                        if("undefined" == typeof receiveUsers || receiveUsers === ''){
                            receiveUsers = [];
                        } else {
                            append = true;
                        }

                        outer:
                            for(let i in data.data){
                                //去掉重复
                                for (let ii in receiveUsers) {
                                    if (receiveUsers[ii].id == data.data[i].id) {
                                        continue outer;
                                    }
                                }

                                if (append) {
                                    // 向表单增加一行
                                    $('#receive_template').bootstrapTable('append',data.data[i]);
                                }
                                receiveUsers.push(data.data[i]);
                            }

                        if (append) {
                            return;
                        }

                        Controller.api.fansTemplate(receiveUsers);
                    }
                });
            });


            var timeInterval = $('#c-time_interval').val();
            var html = '';
            if(timeInterval){
                timeInterval = timeInterval.split(',');
                for(var i=0; i < timeInterval.length; i++){
                    let val = timeInterval[i];
                    html += '<div class="item">' +
                        '<input data-rule="required" type="text" name="row[time_interval][]" placeholder="请输入时段" value="'+val+'" style="padding: 10px"> <div class="del" onclick="delClick(this)">X</div>' +
                        '</div>';
                }

                $('.time-list').append(html);
            }

            $(document).on('click', '.btn-time_append', function (){
                var html = '';

                html = '<div class="item">' +
                    '<input data-rule="required" type="text" name="row[time_interval][]" placeholder="请输入时段" style="padding: 10px"> <div class="del" onclick="delClick(this)">X</div>' +
                    '</div>';


                $('.time-list').append(html);
            });

            window.delClick = function (e, index){
                $(e).parent().remove();
            };


            Controller.api.bindevent();
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'meet/store/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'meet/store/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'meet/store/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        map: function () {
            $("#c-address").data("eSelect", function(data){

                $('#c-location').val(data.location.lng  + ',' + data.location.lat);
                //获取标记点数据
                var geometries_list = markerLayer.getGeometries();
                var ids = [];
                $.each(geometries_list,function (i,v) {
                    ids.push(v.id);
                });
                markerLayer.remove(ids);//移除指定id的标注点

                var position = new TMap.LatLng(data.location.lat, data.location.lng);
                //添加标记点
                markerLayer.add({
                    position: position
                });

                map.setCenter(new TMap.LatLng(data.location.lat,data.location.lng));
            });

            $(document).on('click','.btn-check',function () {
                var location = $('#c-location').val();

                if(!location){
                    Layer.msg(__('Please select coordinates'),{icon:2});
                    return false;
                }

                Fast.api.close({location:location});
            });

            Controller.api.bindevent();
        },
        fans: function(){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'meet/store/fans' + location.search,
                    table: 'wechat_fans',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible: true,
                search: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'nickname', title: __('Nickname'), operate: 'LIKE'},
                        {field: 'avatar', title: __('Avatar'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        {field: 'is_subscribe', title: __('Is_subscribe'),operate: false,searchList: {"1": __('Is_subscribe 1'),"0": __('Is_subscribe 0')},formatter: Table.api.formatter.status},
                        {field: 'subscribe_time', title: __('Subscribe_time'), operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons:[
                                {
                                    name: 'click',
                                    text: __('Select user'),
                                    classname: 'btn btn-xs btn-info btn-click',
                                    icon: '',
                                    // dropdown: '更多',//如果包含dropdown，将会以下拉列表的形式展示
                                    click: function (data,row) {
                                        // Fast.api.close(row);
                                        var dataArr = new Array();
                                        dataArr.push(row);
                                        Fast.api.close({data: dataArr, multiple: false});
                                    },
                                    visible:function(data,row){
                                        return data.is_subscribe === 1 ? true : false;
                                    }
                                }
                            ]
                        }
                    ]
                ],
                onLoadSuccess: function () {
                    $(".btn-add").data("area", ['80%','80%']);
                    $(".btn-editone").data("area", ['80%','80%']);
                }
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var dataArr = new Array();
                $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                    dataArr.push(j);
                });
                var multiple = Backend.api.query('multiple');
                multiple = multiple == 'true' ? true : false;
                Fast.api.close({data: dataArr, multiple: true});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            fansTemplate: function (data){
                var table = $('#receive_template');

                // 初始化表格
                table.bootstrapTable({
                    data: data,
                    pk: 'id',
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    showExport: false, //是否可导出数据
                    columns: [
                        [
                            {field: 'nickname', title: __('Nickname'), align: 'center',formatter: function(value, row, index) {
                                    return '<input name="row[users]['+index+'][id]" value="'+row.id+'" type="hidden" /> '+ row.nickname;
                            }},
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: table,
                                events: Table.api.events.operate,
                                align: 'center',
                                formatter: function (value, row, index) {
                                    var html = '<a href="javascript:$(\'#receive_template\').bootstrapTable(\'remove\',{field: \'id\', values: ['+row.id+']});receiveUsers = receiveUsers.filter(function(item){return item.id != '+row.id+';});" class="btn btn-xs btn-danger"  data-original-title="删除"><i class="fa fa-trash">删除</i></a>'
                                    return html;
                                }
                            }
                        ]
                    ],

                });
            }
        }
    };
    return Controller;
});
